import allure
import os, sys

sys.path.append(os.getcwd())
from common.databases_utils import DBUtil_authority
from config import url, headers_wechat, headers_web
from common.hashlib_utils import hash_md5
from api.authorityControlPlatformApi.userLogin.userLogin import UserLogin
from api.courseApi.termResource.termResource import TermResource
from api.courseApi.courseTableResource.courseTableResource import CourseTableResource
from api.teachingApi.teaching.teaching import Teaching
from api.teachingApi.teacher.teacher import Teacher
from api.teachingApi.attendanceActivities.attendanceActivities import AttendanceActivities
from api.teachingApi.attendanceActivity.attendanceActivity import AttendanceActivity

room = "S1101"
# 签到学生账号
attendanceUserNo = "2021014011"


@allure.feature("互动课堂考勤签到老师和学生")
def test_interactiveclassattendance_success():
    # step 1:互动课程登录获取信息
    with allure.step("step1:互动课程登录获取信息"):
        # 登录账号
        login_json = {
            "userAccountNo": "2008115533",
            "password": "123456"
        }
        valid_code = hash_md5("&signKey=123123")
        resp1 = UserLogin.unifiedlogin(url=url, params={"validCode": valid_code}, json=login_json, headers=headers_web)
        try:
            assert resp1.status_code == 200, "状态码有误"
            userId = resp1.json()["userId"]
            userAccountNo = resp1.json()["userAccountNo"]
        except Exception as e:
            raise e

    with allure.step("step2:获取当前学期信息"):
        valid_code2 = hash_md5("&signKey=123123")
        params2 = {
            "source": None,
            "validCode": valid_code2
        }
        resp2 = TermResource.get_termResource(url=url, params=params2)

        try:
            assert resp2.status_code == 200, "状态码有误"
            schoolYear = resp2.json()[0]["schoolYear"]
            term = resp2.json()[0]["term"]
            schoolTerm = resp2.json()[0]["id"]
            startDate = resp2.json()[0]["startDate"]
            endDate = resp2.json()[0]["endDate"]
        except Exception as e:
            raise e

    with allure.step("step3:查看当前课程信息列表"):
        valid_code3 = hash_md5("userId=" + str(userId) + "&signKey=123123")
        params3 = {
            "courseStudentTypes": None,
            "schoolYear": schoolYear,
            "term": term,
            "userId": userId,
            "validCode": valid_code3
        }
        resp3 = CourseTableResource.get_teachercourseList(url=url, params=params3)
        try:
            assert resp3.status_code == 200, "状态码有误"
            assert (userId in resp3.json()[0]["teacherId"]) == True, "不是该老师的课程"
            assert resp3.json()[0]["schoolYear"] == schoolYear, "不是该学期"
            courseCode = resp3.json()[0]["courseCode"]
            courseId = resp3.json()[0]["courseId"]
            groupId = resp3.json()[0]["teachingClassName"][0]["teachingClassId"]
            groupName = resp3.json()[0]["teachingClassName"][0]["teachingClassName"]
            teacherId = resp3.json()[0]["teacherId"]
            courseTableId = resp3.json()[0]["teachingClassName"][0]["courseTableId"]
            collegeName = resp3.json()[0]["courseCollege"]
            courseCollege = resp3.json()[0]["courseCollegeId"]
            courseName = resp3.json()[0]["courseName"]
            teacherName = resp3.json()[0]["teacherName"]
        except Exception as e:
            raise e

    with allure.step("step4:获取老师上课课次列表信息"):
        valid_code4 = hash_md5("teacherId=" + str(teacherId) + "&signKey=123123")
        params4 = {
            "courseId": courseId,
            "groupId": groupId,
            "schoolYear": schoolYear,
            "teacherId": teacherId,
            "term": term,
            "validCode": valid_code4
        }
        resp4 = Teaching.get_classtimeinformation(url=url, params=params4)
        try:
            assert resp4.status_code == 200, "状态码有误"
        except Exception as e:
            raise e

    with allure.step("step5:老师选择默认课次开始上课"):
        valid_code5 = hash_md5("&signKey=123123")
        params5 = {"validCode": valid_code5}
        json1 = {
            "teacherName": teacherName,
            "courseCode": courseCode,
            "courseTableId": courseTableId,
            "groupId": groupId,
            "collegeCode": courseCollege,
            "teacherNo": userAccountNo,
            "classTimesNum": None,
            "roomId": room,
            "roomName": room,
            "collegeName": collegeName,
            "termId": schoolTerm,
            "courseName": courseName,
            "groupName": groupName,
            "teacherId": teacherId,
            "collegeId": courseCollege,
            "schoolYear": schoolYear,
            "term": term,
            "termStartTime": startDate,
            "id": None,
            "termEndTime": endDate,
            "courseId": courseId,
            "courseTableDetailId": None,
            "groupNo": groupId
        }
        resp5 = Teacher.post_currentCourseInformation(url=url, params=params5, json=json1)
        try:
            assert resp5.status_code == 200, "状态码有误"
            courseInformationId = resp5.json()["id"]
        except Exception as e:
            raise e

    with allure.step("step6:老师创建考勤开始签到"):
        valid_code6 = hash_md5("courseInformationId=" + str(courseInformationId) + "&signKey=123123")
        params6 = {"validCode": valid_code6}
        json2 = {
            "attendanceType": 0,
            "teacherId": teacherId,
            "teacherName": teacherName,
            "courseInformationId": courseInformationId,
            "teacherNo": userAccountNo,
            "roomId": room,
            "roomName": room
        }
        resp6 = AttendanceActivities.post_attendanceactivities(url=url, params=params6, json=json2)
        try:
            assert resp6.status_code == 200, "状态码有误"
            attendanceId = resp6.json()["id"]
            dynamicCode = resp6.json()["dynamicCode"]
        except Exception as e:
            raise e

    with allure.step("step7:学生签到"):
        valid_code7 = hash_md5("attendanceId=" + str(attendanceId) + "&signKey=123123")
        params7 = {"validCode": valid_code7}
        openId = DBUtil_authority.select_one(
            "select applets_open_id from tb_wechat_session where user_id = "
            "(select id from tb_user where user_name = {})".format(attendanceUserNo))[0]
        attendanceUserName = DBUtil_authority.select_one(
            "select user_real_name from tb_user where user_name={}".format(attendanceUserNo))[0]
        attendanceUserId = DBUtil_authority.select_one(
            "select id from tb_user where user_name ={}".format(attendanceUserNo))[0]
        json3 = {
            "attendanceStudentSource": 1,
            "dynamicCode": dynamicCode,
            "openId": openId,
            "attendanceUserNo": attendanceUserNo,
            "attendanceUserName": attendanceUserName,
            "attendanceUserId": attendanceUserId
        }
        resp7 = AttendanceActivities.post_registration(url=url, params=params7, json=json3, paramspath=attendanceId,
                                                       headers=headers_wechat)
        try:
            assert resp7.status_code == 200, "状态码有误"
        except Exception as e:
            raise e
    # print(resp7.request.body, resp7.request.url, resp7.request.headers, resp7.request.method, resp7.url,sep="\n")

    with allure.step("step8:老师结束考勤"):
        valid_code8 = hash_md5("id=" + str(attendanceId) + "&signKey=123123")
        params8 = {"validCode": valid_code8}
        json4 = {
            "teacherId": teacherId,
            "teacherName": teacherName,
            "signNumber": 1,
            "attendanceStatus": 0
        }
        resp8 = AttendanceActivities.post_attendanceStatus(url=url, params=params8, json=json4, paramspath=attendanceId)
        try:
            assert resp8.status_code == 200, "状态码有误"
        except Exception as e:
            raise e

    with allure.step("step9:老师web端确认学生已签到"):
        valid_code9 = hash_md5("id=" + str(attendanceId) + "&signKey=123123")
        params9 = {
            "attendanceStatus": "1",
            "validCode": valid_code9
        }
        resp9 = AttendanceActivities.get_attendance(url=url, params=params9, paramspath=attendanceId)
        try:
            assert resp9.status_code == 200, "状态码有误"
        except Exception as e:
            raise e

    with allure.step("step10:学生小程序确认考勤已签到"):
        valid_code10 = hash_md5("id=" + str(attendanceUserId) + "&signKey=123123")
        params10 = {"courseId": courseId,
                    "groupIds": groupId,
                    "schoolYear": schoolYear,
                    "term": term,
                    "validCode": valid_code10
                    }
        resp10 = AttendanceActivity.get_studentattendances(url=url, params=params10, headers=headers_wechat,
                                                           paramspath=attendanceUserId)
        try:
            assert resp10.status_code == 200, "状态码有误"
        except Exception as e:
            raise e
